const router = require('koa-router')()
const fs = require("fs");
const path = require("path");
const uploadDir = path.join(__dirname, '../images/user');
router.prefix('/users')

//user backend
//删除用户信息
router.post('/deluserbackend', async (ctx, next) => {
  let userid = ctx.request.body.userid;

  //在数据库中删除对应数据
  await ctx.db.EXCUTE(`DELETE FROM user WHERE userid=${userid}`)

  //获取删除后的全部数据
  let result = await ctx.db.EXCUTE('SELECT * FROM user ORDER BY id');
  ctx.body = {
    code: 200,
    data: result
  }
})

//页面初始化时获取数据库内的数据条目
router.post('/getuser', async (ctx, next) => {
  let sql = 'SELECT * FROM user ORDER BY id'
  let result = await ctx.db.EXCUTE(sql);
  ctx.body = {
    code: 200,
    data: result
  };
})

//页面初始化时获取数据库内的userflowerpot数据条目
router.post('/getuserflowerpot', async (ctx, next) => {
  let resultuserid = await ctx.db.EXCUTE("SELECT (SELECT username FROM user ni WHERE n.userid=ni.userid) AS userinfo FROM userflowerpot n")
  let result = await ctx.db.EXCUTE("SELECT n.*, (SELECT potname FROM flowerpot ni WHERE n.potid=ni.potid) AS potinfo FROM userflowerpot n")

  for (let i = 0; i < result.length; i++) {
    Object.assign(result[i], resultuserid[i]);
  }

  ctx.body = {
    code: 200,
    data: result
  };
})

//删除用户花盆信息
router.post('/deluserflowerpot', async (ctx, next) => {
  let upid = ctx.request.body.upid;

  //在数据库中删除对应数据
  await ctx.db.EXCUTE(`DELETE FROM userflowerpot WHERE upid=${upid}`)

  //获取删除后的全部数据
  let result = await ctx.db.EXCUTE('SELECT * FROM user ORDER BY upid');
  ctx.body = {
    code: 200,
    data: result
  }
})

// 用户登录请求
router.post('/login', async (ctx, next) => {
  let body = ctx.request.body;
  let sql = "select * from user where (username=? and password=?) or (mobile=? and password=?)"
  let result = await ctx.db.EXCUTE(sql, [body.username, body.pwd, body.username, body.pwd]);
  console.log(result);
  if (result[0]) {
    console.log(111111);
    ctx.body = {
      code: 200,
      data: result,
      msg: "登陆成功"
    }
  } else {
    console.log(222222);
    ctx.body = {
      code: 200,
      msg: "登陆失败，请检查"
    }
  }
})
// 用户注册请求
router.post('/register', async (ctx, next) => {
  let body = ctx.request.body;
  let sql = "select mobile from user where mobile=?"
  let result = await ctx.db.EXCUTE(sql, [body.mobile])
  let sql1 = "select username from user where username=?"
  let result1 = await ctx.db.EXCUTE(sql1, [body.username])
  console.log(body);
  if (result[0]) {
    ctx.body = {
      code: 200,
      msg: "该手机号已被注册，请重新输入"
    }
  } else if (result1[0]) {
    console.log(5555555);
    ctx.body = {
      code: 200,
      msg: "该用户名已被占用，请重新输入"
    }
  }
  else {
    let userid= new Date().getTime()+ Math.round(Math.random() * (1000 - 1) + 1)
    let sql2 = "insert into user(userid, username, nickname, password, mobile, create_time, potid) values (?, ?, ?, ?, ?, ?, 1)"
    let result2 = await ctx.db.EXCUTE(sql2, [userid, body.username,body.username, body.pwd, Number(body.mobile), new Date().getTime()])
    let result3 = await ctx.db.EXCUTE("insert into userflowerpot (userid, potid) values (?, ?)", [userid, 1])
    console.log(result2);
    console.log(555);
    if (result2) {
      ctx.body = {
        code: 200,
        msg: "注册成功"
      }
    } else {
      ctx.body = {
        code: 200,
        msg: "注册失败"
      }
    }

  }
})
// 
router.post('/getmyuser', async (ctx, next) => {
  let userid = ctx.request.body.userid
  let sql = 'SELECT * FROM user where userid=?'
  let result = await ctx.db.EXCUTE(sql, [userid]);
  console.log(result);
  ctx.body = {
    code: 200,
    data: result
  };
})

router.post('/changeuser', async (ctx, next) => {
  let form = ctx.request.body;
  console.log(form.username);
  ctx.body={
    code: 200
  }
  if (form.avatar.indexOf('data:image') != -1) {
    console.log('if');
    let base64 = form.avatar;
    let base64Data = base64.replace(/^data:image\/\w+;base64,/, "");
    let dataBuffer = Buffer.from(base64Data, 'base64');
    console.log(dataBuffer);
    let name = Date.now() + Math.floor(Math.random()) + '.jpg'
    let imgUrl = uploadDir + '\\' + name
    fs.writeFileSync(imgUrl, dataBuffer)
    let result0 = await ctx.db.EXCUTE('select avatar from user where userid = ?', [form.userid])
    fs.unlink(path.join(__dirname, '../' + result0[0].avatar), async function (err) {
      if (err) {
        console.log('errrrrrrrr');
        console.log(err);
        ctx.body = {
          code: 400
        }
      }
      let sql = "update user set username=?, nickname=?, password=?, mobile=?,avatar=?, signature=?,birthday=?, city=?, cityname=? where userid=?"
      let result = await ctx.db.EXCUTE(sql, [form.username, form.nickname, form.password, form.mobile, '/images/user/' + name, form.signature, form.birthday, form.city, form.cityname, form.userid])
      console.log(result);
      let sql1 = "SELECT * FROM user s,mycrops t WHERE (s.userid=t.userid and s.userid=?)"
      let result1 = await ctx.db.EXCUTE(sql1, [form.userid])
      console.log(99999999);

      ctx.body = {
        code: 200,
        msg: "修改成功"
      }
    })

  }
  else {
    console.log('else');

    let sql = "update user set username=?, nickname=?, password=?, mobile=?,avatar=?, signature=?,birthday=?, city=?, cityname=? where userid=?"
    let result = await ctx.db.EXCUTE(sql, [form.username, form.nickname, form.password, form.mobile, form.avatar, form.signature, form.birthday, form.city, form.cityname, form.userid])
    console.log(result);
    let sql1 = "SELECT * FROM user s,mycrops t WHERE (s.userid=t.userid and s.userid=?)"
    let result1 = await ctx.db.EXCUTE(sql1, [form.userid])
    console.log(88888888);
    console.log(result1);
    ctx.body = {
      code: 200,
      msg: "修改成功"
    }
  }



})
module.exports = router
